package org.example.sdk;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class ResourceService {

    @Autowired
    private ResourceApiFactory resourceApiFactory;

    @Autowired
    private ResourceEncoder resourceEncoder;

    public <T> ListResult<T> find(Class<? extends T> type, String resource, Integer limit, String nextToken) throws IOException {
        ResourceApi resourceApi = resourceApiFactory.getResourceApi();
        var call = resourceApi.find(resource, limit, nextToken);
        var response = call.execute();
        var data = response.body();
        ListResult<T> result = resourceEncoder.decodeListResult(type, data);
        log.info("res: {}", result);
        return result;
    }

    public <T> Iterable<T> findAsStream(Class<? extends T> type, String resource, int limitPerPage) {
        return new ResourceIterable<>(nextToken -> find(type, resource, limitPerPage, nextToken));
    }
}
